<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>监室管理系统 - {{ room_number }}号监室</title>
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #8bc34a;
            --background: #ff7fa;
            --card-bg: #ffffff;
            --border-color: #e1e4e8;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            margin: 0;
            padding: 20px;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background: var(--background);
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        .room-header {
            grid-row: 1 / 2;
            grid-column: 1 / -1;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding: 0 10px;
        }

        .room-title {
            color: var(--primary-color);
            font-size: 1.8rem;
            font-weight: 600;
        }

        .room-info {
            background: #e3f2fd;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 1rem;
            color: #1976d2;
        }

        .room-container {
            width: 95%;
            max-width: 1100px;
            min-height: calc(100vh - 40px);
            height: auto;
            display: flex;
            flex-direction: column;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            background: var(--card-bg);
            border-radius: 15px;
            padding: 25px;
            position: relative;
            overflow-y: auto;
        }
        
        /* 标签栏样式 */
        .tabs {
            display: flex;
            border-bottom: 2px solid #e1e4e8;
            margin-bottom: 20px;
            padding-bottom: 10px;
        }
        
        .tab {
            padding: 10px 20px;
            margin-right: 5px;
            cursor: pointer;
            border-radius: 5px 5px 0 0;
            font-weight: 500;
            color: #555;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .tab:hover {
            background-color: #f5f5f5;
            color: #333;
        }
        
        .tab.active {
            color: var(--secondary-color);
            font-weight: 600;
        }
        
        .tab.active::after {
            content: '';
            position: absolute;
            bottom: -12px;
            left: 0;
            width: 100%;
            height: 3px;
            background-color: var(--secondary-color);
            border-radius: 3px;
        }
        
        /* 内容区域样式 */
        .tab-content {
            display: none;
            width: 100%;
        }
        
        .tab-content.active {
            display: block;
        }
        
        /* 调整原有模块样式以适应新布局 */
        .seat-section, .bed-section, .schedule-section {
            position: relative;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            width: 100%;
        }

        .home-btn {
            position: absolute;
            bottom: 20px;
            right: 20px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            border-radius: 30px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transition: all 0.3s ease;
            z-index: 100;
        }

        .home-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0,0,0,0.2);
            background: linear-gradient(135deg, #2980b9, #3498db);
        }

        .seat-section {
            position: relative;
            grid-row: 2 / 3;
            grid-column: 1 / 2;
            border: 2px solid #ffd54f;
            border-radius: 16px;
            padding: 25px 20px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.1), 0 4px 8px rgba(0,0,0,0.08);
            background: linear-gradient(to bottom, #fff8e1, #fff3e0);
            display: flex;
            flex-direction: column;
            min-height: 1000px;
            max-width: 70%;
            margin-bottom: 30px;
            transform: translateZ(0);
        }

        .section-header {
            position: absolute;
            top: -15px;
            left: 25px;
            background: linear-gradient(to bottom, #ffd54f, #ffb300);
            color: #2c3e50;
            padding: 8px 20px;
            border-radius: 8px;
            font-weight: bold;
            font-size: 1.1rem;
            z-index: 10;
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }

        .seat {
            display: grid;
            grid-template-columns: 50% 20% 30%;
            grid-template-rows: 20% 80%;
            height: 100%;
            min-height: 900px;
            position: relative;
            overflow: visible;
            margin-top: 10px;
        }

        .bed-section {
            position: relative;
            grid-row: 2 / 3;
            grid-column: 2 / 3;
            border: 2px solid #64b5f6;
            border-radius: 16px;
            padding: 25px 20px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.1), 0 4px 8px rgba(0,0,0,0.08);
            background: linear-gradient(to bottom, #e3f2fd, #bbdefb);
            display: flex;
            flex-direction: column;
            min-height: 1000px;
            max-width: 70%;
            margin-bottom: 30px;
            transform: translateZ(0);
        }

        .bed {
            display: grid;
            grid-template-columns: 50% 50%;
            grid-template-rows: 20% 80%;
            height: 100%;
            min-height: 900px;
            position: relative;
            overflow: visible;
            margin-top: 10px;
        }

        .schedule-section {
            position: relative;
            grid-row: 3 / 4;
            grid-column: 1 / 3;
            background: var(--card-bg);
            border: 2px solid var(--accent-color);
            border-radius: 12px;
            padding: 30px 20px 20px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

        .schedule-header {
            position: absolute;
            top: -12px;
            left: 20px;
            background: var(--accent-color);
            color: #2c3e50;
            padding: 5px 15px;
            border-radius: 6px;
            font-weight: bold;
            font-size: 1.1rem;
            z-index: 10;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .area {
            border: 2px solid rgba(0,0,0,0.15);
            padding: 15px;
            box-sizing: border-box;
            position: relative;
            border-radius: 12px;
            background-clip: padding-box;
            box-shadow: inset 0 3px 6px rgba(0,0,0,0.08), 0 4px 10px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            transform: translateZ(0);
        }

        .area:hover {
            box-shadow: inset 0 3px 8px rgba(0,0,0,0.1), 0 6px 12px rgba(0,0,0,0.08);
            transform: translateY(-2px);
        }

        .area::before {
            content: attr(data-name);
            display: block;
            font-family: Arial;
            font-size: 1em;
            color: #444;
            padding: 5px 12px;
            background: rgba(255,255,255,0.92);
            border-radius: 6px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-weight: 600;
            box-shadow: 0 3px 8px rgba(0,0,0,0.15);
            white-space: nowrap;
            letter-spacing: 0.5px;
        }

        .seat .area::before {
            font-size: 0.85em;
            padding: 3px 6px;
        }

        .wash-area {
            grid-column: 1;
            grid-row: 1;
            background: #e3f2fd;
        }

        .seat1-area {
            grid-column: 1;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
            gap: 4px;
        }
        
        /* 大人数模式下的座位区样式 */
        .seat1-area.large-mode {
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(11, minmax(0, 1fr));
        }

        .cell {
            border: 1px solid #e0e0e0;
            min-height: 24px;
            min-width: 30px;
            background: linear-gradient(to bottom, #ffffff, #f9f9f9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 0.75em;
            color: #444;
            line-height: 1.4;
            padding: 8px 4px;
            text-align: center;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            transition: all 0.2s ease;
            transform: translateZ(0);
        }
        
        .cell:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            border-color: #bdbdbd;
            z-index: 5;
        }

        .cell-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            padding: 2px;
        }

        .cell-name {
            font-size: 0.85em;
            font-weight: 600;
            margin-bottom: 4px;
            line-height: 1.2;
            text-shadow: 0 1px 0 rgba(255,255,255,0.8);
        }

        .cell-date {
            font-size: 0.7em;
            color: #555;
            background: rgba(0,0,0,0.03);
            padding: 2px 4px;
            border-radius: 3px;
        }

        .empty-cell {
            background: linear-gradient(to bottom, #f5f5f5, #eeeeee);
            border: 1px dashed #e0e0e0;
        }
        
        .empty-cell .cell-name,
        .empty-cell .cell-date {
            color: #999;
            font-style: italic;
        }

        .tunnel-area {
            grid-column: 2;
            grid-row: 1 / 3;
            background: #f5f5f5;
        }

        .box-area {
            grid-column: 3;
            grid-row: 1;
            background: #fce4ec;
        }

        .seat2-area {
            grid-column: 3;
            grid-row: 2;
            background: #e0f7fa;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
            gap: 4px;
        }
        
        /* 大人数模式下的座位区样式 */
        .seat2-area.large-mode {
            grid-template-columns: repeat(2, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
        }

        .bed-wash-area {
            grid-column: 1;
            grid-row: 1;
            background: #e3f2fd;
        }

        .bed1-area {
            grid-column: 1;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(13, minmax(0, 1fr));
            gap: 4px;
        }
        
        /* 大人数模式下的铺位区样式 */
        .bed1-area.large-mode {
            grid-template-rows: repeat(15, minmax(0, 1fr));
        }

        .bed2-area {
            grid-column: 2;
            grid-row: 1;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(3, 1fr);
            gap: 4px;
            padding: 8px 10px;
        }

        .bed3-area {
            grid-column: 2;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(4, minmax(0, 1fr));
            gap: 4px;
        }
        
        /* 大人数模式下的铺位区样式 */
        .bed3-area.large-mode {
            grid-template-columns: repeat(4, minmax(0, 1fr));
            grid-template-rows: repeat(4, minmax(0, 1fr));
        }

        .schedule-container {
            display: grid;
            grid-template-rows: 1fr auto auto;
            height: 100%;
            gap: 15px;
            padding: 15px;
            box-sizing: border-box;
        }

        .schedule-table-container {
            overflow-y: auto;
            min-height: 0;
        }

        .schedule-table {
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
            font-size: 0.95rem;
            table-layout: fixed;
            flex-grow: 1;
            overflow: auto;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .schedule-table thead {
            background: linear-gradient(to bottom, #3a506b, #2c3e50);
            color: white;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .schedule-table th {
            padding: 14px 8px;
            text-align: center;
            font-weight: 500;
            border-right: 1px solid #4a6180;
            font-size: 0.98rem;
            min-width: 90px;
        }

        .schedule-table th:first-child {
            border-top-left-radius: 8px;
        }

        .schedule-table th:last-child {
            border-top-right-radius: 8px;
            border-right: none;
        }

        .schedule-table tbody {
            width: 100%;
        }

        .schedule-table td {
            padding: 12px 8px;
            text-align: center;
            border-bottom: 1px solid #e0e0e0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .shift-cell {
            background: linear-gradient(to right, #f0f4f8, #e3ebf3);
            font-weight: 600;
            color: #2c3e50;
            padding: 12px 8px;
            text-align: center;
            border-right: 1px solid #e0e0e0;
            position: sticky;
            left: 0;
            z-index: 5;
            font-size: 0.95rem;
            width: 100px;
        }

        .data-cell {
            padding: 10px 6px;
            text-align: center;
            border-right: 1px solid #e0e0e0;
            border-bottom: 1px solid #e0e0e0;
            background-color: #ffffff;
            transition: background 0.2s ease;
            font-size: 0.92rem;
            height: 70px;
            vertical-align: top;
        }

        .person-container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 100%;
            min-height: 60px;
        }

        .person-name {
            font-size: 1em;
            padding: 4px 0;
            margin: 2px 0;
            flex-grow: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .person-name:first-child {
            border-bottom: 1px dashed #e0e0e0;
        }

        .shift-row:nth-child(odd) .data-cell {
            background-color: #f9f9f9;
        }

        .shift-row:nth-child(even) .data-cell {
            background-color: #ffffff;
        }

        .shift-row:hover .data-cell {
            background-color: #f0f7ff !important;
        }

        .data-cell:last-child, .shift-cell:last-child {
            border-right: none;
        }

        .schedule-note {
            margin-top: 15px;
            padding: 12px 15px;
            background: linear-gradient(to right, #e8f5e9, #d7eeda);
            border-radius: 8px;
            font-size: 0.92rem;
            color: #2e7d32;
            border-left: 4px solid #4caf50;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        .empty-slot {
            color: #9e9e9e;
            font-style: italic;
        }

        .schedule-actions {
            margin-top: 15px;
            display: flex;
            gap: 10px;
        }

        .schedule-btn {
            padding: 8px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.2s;
        }

        .schedule-btn:hover {
            background-color: #2980b9;
        }

        .schedule-btn.save {
            background-color: #2ecc71;
        }

        .schedule-btn.save:hover {
            background: #27ae60;
        }

        .schedule-btn.regenerate {
            background-color: #e74c3c;
        }

        .schedule-btn.regenerate:hover {
            background-color: #c0392b;
        }



        .schedule-btn.simulate {
            background-color: #9b59b6;
        }

        .schedule-btn.simulate:hover {
            background-color: #8e44ad;
        }

        .week-selector {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-left: 20px;
        }

        #week-select {
            padding: 8px 15px;
            border-radius: 5px;
            border: 1px solid #ddd;
            background-color: white;
            font-size: 16px;
        }

        .schedule-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .query-btn {
            padding: 8px 15px;
            background-color: #f39c12;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.2s;
        }

        .query-btn:hover {
            background-color: #e67e22;
        }

        .layout-actions {
            margin-top: 10px;
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        .layout-btn {
            padding: 6px 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.85rem;
            transition: background-color 0.2s;
        }

        .layout-btn:hover {
            background-color: #2980b9;
        }

        .layout-btn.save {
            background-color: #2ecc71;
        }

        .layout-btn.save:hover {
            background-color: #27ae60;
        }

        .layout-btn.regenerate {
            background-color: #e74c3c;
        }

        .layout-btn.regenerate:hover {
            background-color: #c0392b;
        }

        /* 编辑按钮统一样式 */
        .layout-actions .layout-btn.edit,
        .schedule-actions .schedule-btn.edit {
            background-color: #f39c12;
            color: white;
            margin-left: 10px;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.2s;
        }

        .layout-actions .layout-btn.edit:hover,
        .schedule-actions .schedule-btn.edit:hover {
            background-color: #e67e22;
        }

        @media (max-width: 1200px) {
            .schedule-table th,
            .shift-cell,
            .data-cell {
                font-size: 0.88rem;
                padding: 10px 6px;
            }

            .person-name {
                font-size: 0.85em;
            }

            .bed2-area {
                padding: 4px 6px;
            }
        }

        .bed2-area .cell {
            font-size: 0.7em;
            padding: 3px;
        }
    </style>
</head>
<body>

    <div class="room-container">
        <div class="room-header">
            <div class="room-title">{{ room_number }}号监室</div>
            <div style="display: flex; align-items: center; gap: 15px;">
                <div class="room-info">总人数: {{ total }}人</div>
                {% if current_user.is_authenticated %}
                <span style="margin-right: 15px;">
                    欢迎，{{ current_user.username }}
                    {% if current_user.user_type != 'normal' %}
                    <span style="background: #f39c12; color: white; padding: 3px 8px; border-radius: 3px; font-size: 0.8em; margin-left: 5px;">管理员</span>
                    {% else %}
                    <span style="background: #3498db; color: white; padding: 3px 8px; border-radius: 3px; font-size: 0.8em; margin-left: 5px;">普通用户</span>
                    {% endif %}
                </span>
                <a href="/logout" style="background: #e74c3c; color: white; padding: 8px 15px; border-radius: 5px; text-decoration: none;">
                    登出系统
                </a>
                {% endif %}
            </div>
        </div>

        <!-- 显示flash消息 -->
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div style="margin-bottom: 15px; padding: 10px 15px; border-radius: 5px;
                        {% if category == 'error' %}
                            background-color: #ffebee; border-left: 4px solid #e74c3c;
                        {% elif category == 'success' %}
                            background-color: #e8f5e9; border-left: 4px solid #2ecc71;
                        {% else %}
                            background-color: #e3f2fd; border-left: 4px solid #3498db;
                        {% endif %}">
                        <p style="margin: 0; color: #333;">{{ message }}</p>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <!-- 显示权限提示 -->
        <div style="margin-bottom: 20px; padding: 10px 15px; border-radius: 5px; background-color: #f8f9fa; border-left: 4px solid
            {% if current_user.is_authenticated and current_user.user_type != 'normal' %}
            #f39c12
            {% else %}
            #3498db
            {% endif %}; grid-row: 1 / 2; grid-column: 1 / -1;">
            {% if current_user.is_authenticated and current_user.user_type != 'normal' %}
            <p style="margin: 0; color: #333;">您以管理员身份登录，可以查看所有房间信息。</p>
            {% else %}
            <p style="margin: 0; color: #333;">您以普通用户身份登录，只能查看您有权限的房间信息。</p>
            {% endif %}
        </div>

        <!-- 日期选择控件 -->
        <div style="margin-bottom: 20px; padding: 10px 15px; border-radius: 5px; background-color: #f8f9fa; display: flex; justify-content: space-between; align-items: center; gap: 15px; grid-row: 1 / 2; grid-column: 1 / -1;">
            <button id="print-btn" class="query-btn" style="padding: 10px 20px; background-color: #27ae60;">
                <i class="fas fa-print" style="margin-right: 5px;"></i>打印当前周排班
            </button>
            <div style="display: flex; align-items: center; gap: 15px;">
                <label for="date-picker" style="font-weight: 500; color: var(--primary-color);">选择日期：</label>
                <input type="date" id="date-picker" class="date-picker" style="padding: 10px 15px; border-radius: 8px; border: 1px solid #ddd; font-size: 16px;">
                <button id="date-query-btn" class="query-btn" style="padding: 10px 20px;">查询当周排班</button>
            </div>
        </div>

        <!-- 标签栏 -->
        <div class="tabs">
            <div class="tab active" data-tab="seat">座位表</div>
            <div class="tab" data-tab="bed">铺位表</div>
            <div class="tab" data-tab="schedule">值班安排表</div>
        </div>
        
        <!-- 座位区 -->
        <div id="seat-tab" class="tab-content active">
            <div class="seat-section">
                <div class="section-header">座位表</div>
                <div class="seat">
                    <div class="area wash-area" data-name="卫生区"></div>
                    <div class="area seat1-area" id="seat1-area"></div>
                    <div class="area tunnel-area" data-name="过道"></div>
                    <div class="area box-area" data-name="储物区"></div>
                    <div class="area seat2-area" id="seat2-area"></div>
                </div>
                <div class="layout-actions">
                    {% if not seatdata_exists %}
                        {% if not is_past_date %}
                            <button id="generate-seat-btn" class="layout-btn">生成座位</button>
                        {% else %}
                            <div class="history-notice">历史数据仅供查看</div>
                        {% endif %}
                    {% else %}
                        {% if not is_past_date %}
                            <button id="regenerate-seat-btn" class="layout-btn regenerate">重新生成</button>
                            <button id="edit-seat-btn" class="layout-btn edit">手动编辑</button>
                        {% else %}
                            <div class="history-notice">历史数据仅供查看</div>
                        {% endif %}
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- 铺位区 -->
        <div id="bed-tab" class="tab-content">
            <div class="bed-section">
                <div class="section-header">铺位表</div>
                <div class="bed">
                    <div class="area bed-wash-area" data-name="卫生区"></div>
                    <div class="area bed1-area" id="bed1-area"></div>
                    <div class="area bed2-area" id="bed2-area"></div>
                    <div class="area bed3-area" id="bed3-area"></div>
                </div>
                <div class="layout-actions">
                    {% if not beddata_exists %}
                        {% if not is_past_date %}
                            <button id="generate-bed-btn" class="layout-btn">生成铺位</button>
                        {% else %}
                            <div class="history-notice">历史数据仅供查看</div>
                        {% endif %}
                    {% else %}
                        {% if not is_past_date %}
                            <button id="regenerate-bed-btn" class="layout-btn regenerate">重新生成</button>
                            <button id="edit-bed-btn" class="layout-btn edit">手动编辑</button>
                        {% else %}
                            <div class="history-notice">历史数据仅供查看</div>
                        {% endif %}
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- 排班表区 -->
        <div id="schedule-tab" class="tab-content">
            <div class="schedule-section">
                <div class="schedule-header">
                    <div class="schedule-title">值班安排表</div>
                    <div class="schedule-controls">
                        <div id="week-info" class="week-info" style="color: var(--primary-color); font-weight: 500;">
                            当前显示: 加载中...
                        </div>
                    </div>
                </div>
                <div class="schedule-container">
                    <div class="schedule-table-container">
                        <table class="schedule-table">
                            <thead>
                                <tr>
                                    <th>班次</th>
                                    <th>周一</th>
                                    <th>周二</th>
                                    <th>周三</th>
                                    <th>周四</th>
                                    <th>周五</th>
                                    <th>周六</th>
                                    <th>周日</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="shift-row">
                                    <td class="shift-cell">午班<br>(12:00-13:30)</td>
                                    {% for day in schedule %}
                                    <td class="data-cell">
                                        <div class="person-container">
                                            {% for person in day.shifts.午班 %}
                                                <div class="person-name">{{ person.name }}</div>
                                            {% else %}
                                                <div class="person-name empty-slot">(空)</div>
                                                <div class="person-name empty-slot">(空)</div>
                                            {% endfor %}
                                        </div>
                                    </td>
                                    {% endfor %}
                                </tr>
                                <tr class="shift-row">
                                    <td class="shift-cell">夜班1<br>(21:30-00:30)</td>
                                    {% for day in schedule %}
                                    <td class="data-cell">
                                        <div class="person-container">
                                            {% for person in day.shifts.夜班1 %}
                                                <div class="person-name">{{ person.name }}</div>
                                            {% else %}
                                                <div class="person-name empty-slot">(空)</div>
                                                <div class="person-name empty-slot">(空)</div>
                                            {% endfor %}
                                        </div>
                                    </td>
                                    {% endfor %}
                                </tr>
                                <tr class="shift-row">
                                    <td class="shift-cell">夜班2<br>(00:30-03:30)</td>
                                    {% for day in schedule %}
                                    <td class="data-cell">
                                        <div class="person-container">
                                            {% for person in day.shifts.夜班2 %}
                                                <div class="person-name">{{ person.name }}</div>
                                            {% else %}
                                                <div class="person-name empty-slot">(空)</div>
                                                <div class="person-name empty-slot">(空)</div>
                                            {% endfor %}
                                        </div>
                                    </td>
                                    {% endfor %}
                                </tr>
                                <tr class="shift-row">
                                    <td class="shift-cell">夜班3<br>(03:30-06:30)</td>
                                    {% for day in schedule %}
                                    <td class="data-cell">
                                        <div class="person-container">
                                            {% for person in day.shifts.夜班3 %}
                                                <div class="person-name">{{ person.name }}</div>
                                            {% else %}
                                                <div class="person-name empty-slot">(空)</div>
                                                <div class="person-name empty-slot">(空)</div>
                                            {% endfor %}
                                        </div>
                                    </td>
                                    {% endfor %}
                                </tr>
                            </tbody>
                        </table>
                    </div>
                
                    <!-- 值班统计表 - 测试用，完成后可删除 -->
                    <div class="schedule-stats" style="margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef; box-sizing: border-box;">
                        <h4 style="margin: 0 0 15px 0; color: #495057; font-size: 16px;">📊 本周值班统计（测试用）</h4>
                        <div class="stats-table-container" style="overflow-x: auto;">
                            <table class="stats-table" style="width: 100%; border-collapse: collapse; font-size: 14px; table-layout: fixed;">
                                <thead>
                                    <tr style="background-color: #e9ecef;">
                                        <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: 600; width: 14.28%;">人员姓名</th>
                                        <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: 600; width: 14.28%;">总值班次数</th>
                                        <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: 600; width: 14.28%;">午班次数</th>
                                        <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: 600; width: 14.28%;">夜班1次数</th>
                                        <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: 600; width: 14.28%;">夜班2次数</th>
                                        <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: 600; width: 14.28%;">夜班3次数</th>
                                        <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: 600; width: 14.28%;">困难班次</th>
                                    </tr>
                                </thead>
                                <tbody id="stats-table-body">
                                    <!-- 统计数据将通过JavaScript动态生成 -->
                                </tbody>
                            </table>
                        </div>
                        <div style="margin-top: 10px; font-size: 12px; color: #6c757d; text-align: center;">
                            💡 此统计表用于测试排班模块公平性，测试完成后请删除
                        </div>
                    </div>
                    
                    <!-- 排班分析报告 -->
                    <div class="schedule-analysis" style="margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef; box-sizing: border-box;">
                        <h4 style="margin: 0 0 15px 0; color: #495057; font-size: 16px;">📋 排班分析报告</h4>
                        <div id="analysis-report" style="font-size: 14px; line-height: 1.6;">
                            <!-- 分析报告内容将通过JavaScript动态生成 -->
                        </div>
                    </div>
                    
                    <div class="schedule-note">
                        <strong>值班规则说明：</strong>
                        1. 每班次安排2人值班；
                        2. 值班人员按入所时间顺序轮转；
                        3. 完成一轮值班后不再安排相同班次；
                        4. 人员变动后系统自动更新排班
                    </div>
                    <div class="schedule-actions">
                        {% if not schedule_exists %}
                            {% if not is_past_date %}
                                <button id="generate-btn" class="schedule-btn">生成当周值班表</button>
                            {% else %}
                                <div class="history-notice">历史数据仅供查看</div>
                            {% endif %}
                        {% else %}
                            {% if not is_past_date %}
                                <button id="regenerate-btn" class="schedule-btn regenerate">重新生成</button>
                                <button id="edit-schedule-btn" class="schedule-btn edit">手动编辑</button>
                            {% else %}
                                <div class="history-notice">历史数据仅供查看</div>
                            {% endif %}
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 回到首页按钮 -->
        <button class="home-btn" onclick="window.location.href='/'">回到首页</button>
    </div>

    <script>
        // 设置日期选择器默认值为今天
        document.addEventListener('DOMContentLoaded', function() {
            // 从URL中获取当前选择的日期
            const urlParams = new URLSearchParams(window.location.search);
            const selectedWeek = urlParams.get('week');

            // 如果URL中有日期参数，则使用该日期；否则使用今天的日期
            let currentDate;
            if (selectedWeek) {
                document.getElementById('date-picker').value = selectedWeek;
                currentDate = new Date(selectedWeek);
            } else {
                // 设置日期选择器默认值为今天
                const today = new Date();
                const year = today.getFullYear();
                const month = String(today.getMonth() + 1).padStart(2, '0');
                const day = String(today.getDate()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`;
                document.getElementById('date-picker').value = formattedDate;
                currentDate = today;
            }

            // 更新周信息显示
            updateWeekInfo(currentDate);

            // 函数：更新周信息显示
            function updateWeekInfo(date) {
                // 计算当前日期所在周的周一
                const day = date.getDay() || 7; // 将周日的0转换为7
                const diff = date.getDate() - day + 1; // 计算周一日期
                const monday = new Date(date);
                monday.setDate(diff);

                // 计算周日日期
                const sunday = new Date(monday);
                sunday.setDate(monday.getDate() + 6);

                // 格式化日期为MM-DD格式
                const formatDate = (date) => {
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${month}-${day}`;
                };

                // 生成周信息文本
                const weekLabel = `${formatDate(monday)}至${formatDate(sunday)}`;

                // 判断是否为当前周
                const today = new Date();
                const todayDay = today.getDay() || 7;
                const todayDiff = today.getDate() - todayDay + 1;
                const thisMonday = new Date(today);
                thisMonday.setDate(todayDiff);

                // 比较两个日期是否在同一周（比较周一日期）
                const isCurrentWeek = monday.getFullYear() === thisMonday.getFullYear() &&
                                     monday.getMonth() === thisMonday.getMonth() &&
                                     monday.getDate() === thisMonday.getDate();

                // 更新页面显示
                const weekInfoElement = document.getElementById('week-info');
                weekInfoElement.textContent = `当前显示: ${weekLabel}${isCurrentWeek ? ' (本周)' : ''}`;
            }

            // 查询按钮点击事件
            document.getElementById('date-query-btn').addEventListener('click', function() {
                const selectedDate = document.getElementById('date-picker').value;
                if (!selectedDate) {
                    alert('请选择日期');
                    return;
                }

                // 获取当前房间号
                const roomNumber = '{{ room_number }}';

                // 跳转到对应日期的页面
                window.location.href = `/room/${roomNumber}?week=${selectedDate}`;
            });

            // 允许按回车键触发查询
            document.getElementById('date-picker').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('date-query-btn').click();
                }
            });
        });

        // 数据初始化
        const backendData = {{ data|tojson }};
        const backendBedData = {{ beddata|tojson }};
        const backendSeatData = {{ seatdata|tojson }};
        const backendSchedule = {{ schedule|tojson }};
        const roomNumber = "{{ room_number }}";
        const beddataExists = {{ beddata_exists|tojson }};
        const seatdataExists = {{ seatdata_exists|tojson }};
        const scheduleExists = {{ schedule_exists|tojson }};
        const weekOptions = {{ week_options|tojson }};
        const selectedWeek = "{{ selected_week }}";
        const currentWeekMonday = "{{ current_week_monday }}";

        // 值班统计功能
        function generateScheduleStats() {
            // 获取排班分析报告
            fetch(`/get_schedule_analysis/${roomNumber}?target_date=${selectedWeek}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.analysis_report) {
                        // 将分析报告内容显示在页面上
                        document.getElementById('analysis-report').innerHTML = 
                            '<pre style="margin: 0; white-space: pre-wrap; word-wrap: break-word;">' + 
                            data.analysis_report + '</pre>';
                    }
                })
                .catch(error => {
                    console.error('获取排班分析报告失败:', error);
                });
            if (!backendSchedule || backendSchedule.length === 0) {
                return;
            }

            // 统计每个人的值班次数
            const stats = {};
            
            // 遍历一周7天的值班表
            backendSchedule.forEach((day, dayIndex) => {
                if (day && day.shifts) {
                    // 遍历每个班次
                    Object.keys(day.shifts).forEach(shiftName => {
                        const shiftPeople = day.shifts[shiftName];
                        if (shiftPeople && Array.isArray(shiftPeople)) {
                            shiftPeople.forEach(person => {
                                if (person && person.name) {
                                    if (!stats[person.name]) {
                                        stats[person.name] = {
                                            total: 0,
                                            '午班': 0,
                                            '夜班1': 0,
                                            '夜班2': 0,
                                            '夜班3': 0,
                                            'difficult_shifts': 0  // 困难班次统计
                                        };
                                    }
                                    stats[person.name].total++;
                                    stats[person.name][shiftName]++;
                                    
                                    // 统计困难班次
                                    if (shiftName === '夜班2' || shiftName === '夜班3') {
                                        stats[person.name].difficult_shifts++;
                                    }
                                }
                            });
                        }
                    });
                }
            });

            // 渲染统计表格
            renderStatsTable(stats);
        }

        // 渲染统计表格
        function renderStatsTable(stats) {
            const tbody = document.getElementById('stats-table-body');
            if (!tbody) return;

            tbody.innerHTML = '';

            // 按总值班次数排序（从多到少）
            const sortedStats = Object.entries(stats).sort((a, b) => b[1].total - a[1].total);

            sortedStats.forEach(([personName, personStats]) => {
                const row = document.createElement('tr');
                row.style.borderBottom = '1px solid #dee2e6';
                
                row.innerHTML = `
                    <td style="padding: 6px; border: 1px solid #dee2e6; text-align: center; font-weight: 500; width: 14.28%;">${personName}</td>
                    <td style="padding: 6px; border: 1px solid #dee2e6; text-align: center; background-color: ${personStats.total > 4 ? '#ffebee' : personStats.total < 2 ? '#e8f5e9' : '#fff3e0'}; width: 14.28%;">
                        <strong>${personStats.total}</strong>
                    </td>
                    <td style="padding: 6px; border: 1px solid #dee2e6; text-align: center; width: 14.28%;">${personStats['午班']}</td>
                    <td style="padding: 6px; border: 1px solid #dee2e6; text-align: center; width: 14.28%;">${personStats['夜班1']}</td>
                    <td style="padding: 6px; border: 1px solid #dee2e6; text-align: center; width: 14.28%;">${personStats['夜班2']}</td>
                    <td style="padding: 6px; border: 1px solid #dee2e6; text-align: center; width: 14.28%;">${personStats['夜班3']}</td>
                    <td style="padding: 6px; border: 1px solid #dee2e6; text-align: center; width: 14.28%;">${personStats['difficult_shifts']}</td>
                `;
                
                tbody.appendChild(row);
            });

            // 如果没有数据，显示提示
            if (sortedStats.length === 0) {
                const noDataRow = document.createElement('tr');
                noDataRow.innerHTML = `
                    <td colspan="7" style="padding: 10px; text-align: center; color: #6c757d; font-style: italic;">
                        暂无值班数据
                    </td>
                `;
                tbody.appendChild(noDataRow);
            }
        }

        // 铺位和座位布局数据
        let bedLayoutData = backendBedData || [];
        let seatLayoutData = backendSeatData || [];

        // 渲染铺位和座位布局
        function renderLayouts() {
            renderBedLayout();
            renderSeatLayout();
        }

        // 渲染铺位布局
        function renderBedLayout() {
            const bed1Area = document.getElementById('bed1-area');
            const bed2Area = document.getElementById('bed2-area');
            const bed3Area = document.getElementById('bed3-area');

            if (!bed1Area || !bed2Area || !bed3Area) return;

            // 清空现有内容
            bed1Area.innerHTML = '';
            bed2Area.innerHTML = '';
            bed3Area.innerHTML = '';
            
            // 判断是否启用大人数模式（超过25人）
            const isLargeMode = bedLayoutData.length > 25;
            
            // 根据模式设置CSS类
            if (isLargeMode) {
                bed1Area.classList.add('large-mode');
                bed2Area.classList.add('large-mode');
                bed3Area.classList.add('large-mode');
            } else {
                bed1Area.classList.remove('large-mode');
                bed2Area.classList.remove('large-mode');
                bed3Area.classList.remove('large-mode');
            }
            
            // 根据模式确定布局参数
            let bed1Rows, bed2Rows, bed3Rows, bed3Cols;
            
            if (isLargeMode) {
                // 大人数模式：左侧15行1列，右上5行1列，右下4列4行
                bed1Rows = 15;
                bed2Rows = 5;
                bed3Rows = 4;
                bed3Cols = 4;
            } else {
                // 标准模式：左侧13行1列，右上3行1列，右下3列4行
                bed1Rows = 13;
                bed2Rows = 3;
                bed3Rows = 4;
                bed3Cols = 3;
            }
            
            // 1. 渲染铺位到bed1Area（从下往上）- 保持不变
            // 创建一个临时数组来存储单元格
            const bed1Cells = [];
            for (let i = 0; i < Math.min(bed1Rows, bedLayoutData.length); i++) {
                bed1Cells.push(createLayoutCell(i, bedLayoutData));
            }
            
            // 从下往上添加到bed1Area
            for (let i = bed1Cells.length - 1; i >= 0; i--) {
                bed1Area.appendChild(bed1Cells[i]);
            }
            
            // 计算已分配的人数
            let assignedCount = bed1Rows;
            
            // 2. 渲染铺位到bed3Area（一行一行，每行从右往左）
            // 创建一个二维数组来表示网格
            const grid3 = Array(bed3Rows).fill().map(() => Array(bed3Cols).fill(null));
            
            // 计算bed3区域可容纳的人数
            const bed3Capacity = bed3Rows * bed3Cols;
            
            // 按照一行一行，每行从右往左的顺序填充网格
            let cellIndex3 = 0;
            for (let row = bed3Rows - 1; row >= 0; row--) {  // 从最下面一行开始
                for (let col = bed3Cols - 1; col >= 0; col--) {  // 每行从右往左
                    if (assignedCount + cellIndex3 < bedLayoutData.length && cellIndex3 < bed3Capacity) {
                        grid3[row][col] = createLayoutCell(assignedCount + cellIndex3, bedLayoutData);
                        cellIndex3++;
                    }
                }
            }
            
            // 按照网格顺序添加单元格到bed3Area
            for (let row = 0; row < bed3Rows; row++) {
                for (let col = 0; col < bed3Cols; col++) {
                    if (grid3[row][col]) {
                        bed3Area.appendChild(grid3[row][col]);
                    } else {
                        // 添加空单元格
                        const emptyCell = document.createElement('div');
                        emptyCell.className = 'cell empty-cell';
                        bed3Area.appendChild(emptyCell);
                    }
                }
            }
            
            // 更新已分配的人数
            assignedCount += cellIndex3;
            
            // 3. 剩下的人再从下往上排入bed2
            // 创建一个临时数组来存储单元格
            const bed2Cells = [];
            for (let i = assignedCount; i < Math.min(assignedCount + bed2Rows, bedLayoutData.length); i++) {
                bed2Cells.push(createLayoutCell(i, bedLayoutData));
            }
            
            // 从下往上添加到bed2Area
            for (let i = bed2Cells.length - 1; i >= 0; i--) {
                bed2Area.appendChild(bed2Cells[i]);
            }
        }

        // 渲染座位布局
        function renderSeatLayout() {
            const seat1Area = document.getElementById('seat1-area');
            const seat2Area = document.getElementById('seat2-area');

            if (!seat1Area || !seat2Area) return;

            // 清空现有内容
            seat1Area.innerHTML = '';
            seat2Area.innerHTML = '';
            
            // 判断是否启用大人数模式（超过25人）
            const isLargeMode = seatLayoutData.length > 25;
            
            // 根据模式设置CSS类
            if (isLargeMode) {
                seat1Area.classList.add('large-mode');
                seat2Area.classList.add('large-mode');
            } else {
                seat1Area.classList.remove('large-mode');
                seat2Area.classList.remove('large-mode');
            }
            
            // 根据模式确定布局参数
            let seat1Rows, seat1Cols, seat2Rows, seat2Cols;
            
            if (isLargeMode) {
                // 大人数模式：左侧11行3列（包括被子列），右侧9行2列
                seat1Rows = 11;
                seat1Cols = 3; // 包括被子列
                seat2Rows = 9;
                seat2Cols = 2;
            } else {
                // 标准模式：左侧9行3列（包括被子列），右侧9行1列
                seat1Rows = 9;
                seat1Cols = 3; // 包括被子列
                seat2Rows = 9;
                seat2Cols = 1;
            }
            
            // 创建"被子"单元格函数
            function createBedCell() {
                const cell = document.createElement('div');
                cell.className = 'cell';
                
                const cellContent = document.createElement('div');
                cellContent.className = 'cell-content';
                
                const nameDiv = document.createElement('div');
                nameDiv.className = 'cell-name';
                nameDiv.textContent = '被子';
                
                cellContent.appendChild(nameDiv);
                cell.appendChild(cellContent);
                cell.style.backgroundColor = '#e6f7ff'; // 给被子单元格一个特殊的背景色
                
                return cell;
            }
            
            // 创建一个倒序的人员数据数组
            const reversedData = [...seatLayoutData].reverse();
            
            // 计算seat1区域可容纳的人数（不包括被子列）
            const seat1Capacity = seat1Rows * (seat1Cols - 1); // 减去被子列
            
            // 创建一个二维数组来表示左侧网格(seat1)
            const grid1 = Array(seat1Rows).fill().map(() => Array(seat1Cols).fill(null));
            
            // 首先填充seat1区域
            // 1. 最左侧一列固定为被子区
            for (let row = 0; row < seat1Rows; row++) {
                grid1[row][0] = createBedCell();
            }
            
            // 2. 第二、第三列为人员区，按照"之"字形排列（先左后右，再下一行先左后右）
            let seat1PersonCount = 0;
            for (let row = 0; row < seat1Rows && seat1PersonCount < Math.min(seat1Capacity, reversedData.length); row++) {
                // 先放左边（第2列）
                if (seat1PersonCount < Math.min(seat1Capacity, reversedData.length)) {
                    grid1[row][1] = createLayoutCell(seat1PersonCount, reversedData);
                    seat1PersonCount++;
                }
                
                // 再放右边（第3列）
                if (seat1PersonCount < Math.min(seat1Capacity, reversedData.length)) {
                    grid1[row][2] = createLayoutCell(seat1PersonCount, reversedData);
                    seat1PersonCount++;
                }
            }
            
            // 按照网格顺序添加单元格到seat1Area
            for (let row = 0; row < seat1Rows; row++) {
                for (let col = 0; col < seat1Cols; col++) {
                    if (grid1[row][col]) {
                        seat1Area.appendChild(grid1[row][col]);
                    }
                }
            }
            
            // 如果seat1区域已满，剩余人员放入seat2区域
            if (seat1PersonCount < reversedData.length) {
                // 创建一个二维数组来表示右侧网格(seat2)
                const grid2 = Array(seat2Rows).fill().map(() => Array(seat2Cols).fill(null));
                
                // 按照"之"字形排列（先左后右，再下一行先左后右）
                let seat2PersonCount = 0;
                for (let row = 0; row < seat2Rows && (seat1PersonCount + seat2PersonCount) < reversedData.length; row++) {
                    // 填充每一行的单元格
                    for (let col = 0; col < seat2Cols && (seat1PersonCount + seat2PersonCount) < reversedData.length; col++) {
                        grid2[row][col] = createLayoutCell(seat1PersonCount + seat2PersonCount, reversedData);
                        seat2PersonCount++;
                    }
                }
                
                // 按照网格顺序添加单元格到seat2Area
                for (let row = 0; row < seat2Rows; row++) {
                    for (let col = 0; col < seat2Cols; col++) {
                        if (grid2[row][col]) {
                            seat2Area.appendChild(grid2[row][col]);
                        }
                    }
                }
            }
        }

        // 创建布局单元格
        function createLayoutCell(index, data) {
            const cell = document.createElement('div');
            cell.className = 'cell';

            const cellContent = document.createElement('div');
            cellContent.className = 'cell-content';

            const nameDiv = document.createElement('div');
            nameDiv.className = 'cell-name';

            const dateDiv = document.createElement('div');
            dateDiv.className = 'cell-date';

            if (index < data.length && data[index]) {
                nameDiv.textContent = `${index + 1}. ${data[index].name}`;
                dateDiv.textContent = formatDate(data[index].join_date);
                
                // 根据FXDJ和BHLX字段值设置背景色
                const person = data[index];
                
                // 检查person对象是否包含FXDJ和BHLX字段
                if (person.hasOwnProperty('FXDJ') && person.hasOwnProperty('BHLX')) {
                    const fxdj = parseInt(person.FXDJ, 10);
                    const bhlx = parseInt(person.BHLX, 10);
                    
                    // 调试信息：检查FXDJ和BHLX的值
                    console.log(`FXDJ: ${fxdj}, BHLX: ${bhlx}`);
                    
                    // 根据FXDJ和BHLX字段值设置背景色
                    if (fxdj === 1) {
                        cell.style.background = '#ffcccc'; // 红色
                        console.log('设置背景色为红色');
                    } else if (fxdj === 2) {
                        cell.style.background = '#ffffcc'; // 黄色
                        console.log('设置背景色为黄色');
                    } else if (bhlx === 1) {
                        cell.style.background = '#ccffcc'; // 绿色
                        console.log('设置背景色为绿色');
                    } else if (fxdj === 0 && bhlx === 0) {
                        // 如果FXDJ和BHLX都为0，设置默认背景色
                        cell.style.background = '#f5f5f5'; // 灰色
                        console.log('设置背景色为灰色');
                    }
                } else {
                    console.log('Person对象缺少FXDJ或BHLX字段');
                }
            } else {
                nameDiv.textContent = '空位';
                dateDiv.textContent = '-';
                cell.classList.add('empty-cell');
            }

            cellContent.appendChild(nameDiv);
            cellContent.appendChild(dateDiv);
            cell.appendChild(cellContent);

            return cell;
        }

        // 日期格式化
        function formatDate(dateString) {
            if (!dateString) return '无日期';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit'
                }).replace(/\//g, '-');
            } catch (e) {
                console.error('日期格式错误:', dateString, e);
                return '无效日期';
            }
        }

        // 生成铺位布局
        async function generateBedLayout() {
            // 按入所日期排序
            const sortedData = [...backendData].sort((a, b) =>
                new Date(a.join_date) - new Date(b.join_date));

            // 生成铺位布局数据
            bedLayoutData = sortedData.map((person, index) => ({
                id: person.id,
                name: person.name,
                join_date: person.join_date,
                FXDJ: person.FXDJ,
                BHLX: person.BHLX,
                position: `铺位${index + 1}`
            }));

            // 渲染新布局
            renderBedLayout();

            // 立即保存到数据库
            await saveBedLayout();
        }

        // 生成座位布局
        async function generateSeatLayout() {
            // 按入所日期排序
            const sortedData = [...backendData].sort((a, b) =>
                new Date(a.join_date) - new Date(b.join_date));

            // 生成座位布局数据
            seatLayoutData = sortedData.map((person, index) => ({
                id: person.id,
                name: person.name,
                join_date: person.join_date,
                FXDJ: person.FXDJ,
                BHLX: person.BHLX,
                position: `座位${index + 1}`
            }));

            // 渲染新布局
            renderSeatLayout();

            // 立即保存到数据库
            await saveSeatLayout();
        }

        // 保存铺位布局
        async function saveBedLayout() {
            try {
                const response = await fetch(`/save_bed_layout/${roomNumber}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        bed_data: bedLayoutData,
                        target_date: selectedWeek
                    })
                });

                const result = await response.json();
                if (result.success) {
                    alert('铺位保存成功!');
                    // 刷新页面
                    location.reload();
                } else {
                    alert('铺位保存失败');
                }
            } catch (error) {
                console.error('保存铺位错误:', error);
                alert('保存铺位时发生错误');
            }
        }

        // 保存座位布局
        async function saveSeatLayout() {
            try {
                const response = await fetch(`/save_seat_layout/${roomNumber}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        seat_data: seatLayoutData,
                        target_date: selectedWeek
                    })
                });

                const result = await response.json();
                if (result.success) {
                    alert('座位保存成功!');
                    // 刷新页面
                    location.reload();
                } else {
                    alert('座位保存失败');
                }
            } catch (error) {
                console.error('保存座位错误:', error);
                alert('保存座位时发生错误');
            }
        }

        // 获取URL参数的函数
        function getUrlParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
        
        // 更新URL参数的函数，不刷新页面
        function updateUrlParam(name, value) {
            const url = new URL(window.location.href);
            url.searchParams.set(name, value);
            window.history.pushState({}, '', url);
        }
        
        // 标签切换功能
        function setupTabs() {
            const tabs = document.querySelectorAll('.tab');
            const tabContents = document.querySelectorAll('.tab-content');
            
            tabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    const tabId = tab.getAttribute('data-tab');
                    
                    // 移除所有标签的active类
                    tabs.forEach(t => t.classList.remove('active'));
                    
                    // 移除所有内容区域的active类
                    tabContents.forEach(content => content.classList.remove('active'));
                    
                    // 为当前点击的标签添加active类
                    tab.classList.add('active');
                    
                    // 为对应的内容区域添加active类
                    document.getElementById(`${tabId}-tab`).classList.add('active');
                    
                    // 更新URL参数，记录当前标签
                    updateUrlParam('tab', tabId);
                    
                    // 如果切换到了铺位或座位标签，重新渲染布局
                    if (tabId === 'bed' || tabId === 'seat') {
                        renderLayouts();
                    }
                    
                    // 如果切换到了排班标签，重新生成值班统计
                    if (tabId === 'schedule') {
                        setTimeout(() => {
                            generateScheduleStats();
                        }, 100);
                    }
                });
            });
        }
        
        // 根据URL参数激活对应标签
        function activateTabFromUrl() {
            const tabId = getUrlParam('tab') || 'seat'; // 默认为座位表
            const tab = document.querySelector(`.tab[data-tab="${tabId}"]`);
            const tabContent = document.getElementById(`${tabId}-tab`);
            
            if (tab && tabContent) {
                // 移除所有标签的active类
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                
                // 移除所有内容区域的active类
                document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
                
                // 激活指定标签
                tab.classList.add('active');
                tabContent.classList.add('active');
            }
        }
        
        // 页面加载时初始化布局和标签
        document.addEventListener('DOMContentLoaded', () => {
            // 设置标签切换功能
            setupTabs();
            
            // 根据URL参数激活对应标签
            activateTabFromUrl();
            
            // 渲染布局
            renderLayouts();
            
            // 输出调试信息
            console.log(`座位布局: ${seatLayoutData.length}人, 大人数模式: ${seatLayoutData.length > 25}`);
            console.log(`铺位布局: ${bedLayoutData.length}人, 大人数模式: ${bedLayoutData.length > 25}`);
            console.log('座位区人员放入逻辑已更新: 人员数据倒序后，按"之"字形排列（先左后右，再下一行先左后右）');
            console.log('铺位区人员放入逻辑已更新: bed1保持不变，剩下的人按照一行一行（每行从右往左）填入bed3，剩下的再从下往上排入bed2');
            
            // 延迟生成值班统计和分析报告，确保不影响主要布局渲染
            setTimeout(() => {
                generateScheduleStats();
            }, 100);
            
            // 创建隐藏form用于打印数据提交
            const printForm = document.createElement('form');
            printForm.method = 'POST';
            printForm.action = `/print/${'{{ room_number }}'}`;
            printForm.target = '_blank';
            printForm.style.display = 'none';
            document.body.appendChild(printForm);

            // 打印按钮点击事件
            document.getElementById('print-btn').addEventListener('click', function() {
                const selectedDate = document.getElementById('date-picker').value;
                if (!selectedDate) {
                    alert('请选择日期');
                    return;
                }
                
                // 计算周偏移
                const today = new Date();
                const selectedDateObj = new Date(selectedDate);
                const diffTime = selectedDateObj.getTime() - today.getTime();
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                const weekOffset = Math.floor(diffDays / 7);
                
                // 清空form原有input
                while (printForm.firstChild) {
                    printForm.removeChild(printForm.firstChild);
                }

                // 添加参数到form
                function addInput(name, value) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = name;
                    input.value = value;
                    printForm.appendChild(input);
                }

                addInput('week', selectedDate);
                addInput('week_offset', weekOffset);
                addInput('seat_rows', 6);
                addInput('seat_data', JSON.stringify(backendSeatData || []));
                addInput('bed1_rows', 3);
                addInput('bed1_data', JSON.stringify(backendBedData || []));
                addInput('bed2_rows', 3);
                addInput('bed2_data', JSON.stringify(backendBedData || []));
                addInput('bed3_rows', 3);
                addInput('bed3_cols', 3);
                addInput('bed3_data', JSON.stringify(backendBedData || []));

                // 提交form
                printForm.submit();
            });

            // 绑定铺位生成按钮事件
            document.getElementById('generate-bed-btn')?.addEventListener('click', async function() {
                await generateBedLayout();
                // 保存当前标签状态
                const currentTab = document.querySelector('.tab.active').getAttribute('data-tab');
                // 添加标签参数到URL
                const url = new URL(window.location.href);
                url.searchParams.set('tab', currentTab);
                window.location.href = url.toString();
            });

            // 绑定铺位重新生成按钮事件
            document.getElementById('regenerate-bed-btn')?.addEventListener('click', async function() {
                await generateBedLayout();
                // 保存当前标签状态
                const currentTab = document.querySelector('.tab.active').getAttribute('data-tab');
                // 添加标签参数到URL
                const url = new URL(window.location.href);
                url.searchParams.set('tab', currentTab);
                window.location.href = url.toString();
            });

            // 绑定座位生成按钮事件
            document.getElementById('generate-seat-btn')?.addEventListener('click', async function() {
                await generateSeatLayout();
                // 保存当前标签状态
                const currentTab = document.querySelector('.tab.active').getAttribute('data-tab');
                // 添加标签参数到URL
                const url = new URL(window.location.href);
                url.searchParams.set('tab', currentTab);
                window.location.href = url.toString();
            });

            // 绑定座位重新生成按钮事件
            document.getElementById('regenerate-seat-btn')?.addEventListener('click', async function() {
                await generateSeatLayout();
                // 保存当前标签状态
                const currentTab = document.querySelector('.tab.active').getAttribute('data-tab');
                // 添加标签参数到URL
                const url = new URL(window.location.href);
                url.searchParams.set('tab', currentTab);
                window.location.href = url.toString();
            });



            // 周查询按钮事件
            document.getElementById('week-query-btn')?.addEventListener('click', function() {
                const selectedWeek = document.getElementById('week-select').value;
                const url = new URL(window.location.href);

                if (selectedWeek === currentWeekMonday) {
                    url.searchParams.delete('week');
                } else {
                    url.searchParams.set('week', selectedWeek);
                }

                window.location.href = url.toString();
            });

            // 值班表生成按钮事件
            document.getElementById('generate-btn')?.addEventListener('click', async function() {
                try {
                    // 保存当前标签状态
                    const currentTab = document.querySelector('.tab.active').getAttribute('data-tab');
                    
                    const response = await fetch(`/generate_schedule/${roomNumber}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            target_date: selectedWeek
                        })
                    });

                    const result = await response.json();
                    if (result.success) {
                        // 后端已自动保存，检查saved字段
                        if (result.saved) {
                            // 刷新页面显示新值班表，并保持当前标签
                            const url = new URL(window.location.href);
                            url.searchParams.set('tab', currentTab);
                            window.location.href = url.toString();
                        } else {
                            alert('生成值班表成功，但保存失败');
                        }
                    } else {
                        alert('生成值班表失败');
                    }
                } catch (error) {
                    console.error('生成值班表错误:', error);
                    alert('生成值班表时发生错误');
                }
            });

            // 值班表重新生成按钮事件
            document.getElementById('regenerate-btn')?.addEventListener('click', async function() {
                try {
                    // 保存当前标签状态
                    const currentTab = document.querySelector('.tab.active').getAttribute('data-tab');
                    
                    const response = await fetch(`/generate_schedule/${roomNumber}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            target_date: selectedWeek
                        })
                    });

                    const result = await response.json();
                    if (result.success) {
                        // 后端已自动保存，检查saved字段
                        if (result.saved) {
                            // 刷新页面显示新值班表，并保持当前标签
                            const url = new URL(window.location.href);
                            url.searchParams.set('tab', currentTab);
                            window.location.href = url.toString();
                        } else {
                            alert('重新生成值班表成功，但保存失败');
                        }
                    } else {
                        alert('重新生成值班表失败');
                    }
                } catch (error) {
                    console.error('重新生成错误:', error);
                    alert('重新生成值班表时发生错误');
                }
            });



        });

        // 编辑按钮事件处理
        document.getElementById('edit-bed-btn')?.addEventListener('click', function() {
            window.location.href = `/bed_edit?room_number={{ room_number }}&user_id={{ current_user['id'] }}`;
        });

        document.getElementById('edit-seat-btn')?.addEventListener('click', function() {
            window.location.href = `/seat_edit?room_number={{ room_number }}&user_id={{ current_user['id'] }}`;
        });

        document.getElementById('edit-schedule-btn')?.addEventListener('click', function() {
            window.location.href = `/edit_schedule/${roomNumber}`;
        });
    </script>
</body>
</html>